package com.cory.admin.sys.service;


import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cory.admin.sys.domain.entity.SysLoginLog;
import com.cory.admin.sys.domain.entity.SysUser;
import com.cory.admin.sys.mapper.SysLoginLogMapper;
import com.cory.utils.lang.DateUtils;

/**
 *  服务实现类
 *
 * @author xc
 * @since 2019-03-18
 */
@Service
public class SysLoginLogService extends ServiceImpl<SysLoginLogMapper, SysLoginLog> {

    @Transactional(rollbackFor=Exception.class)
    public SysLoginLog addLoginLog(SysUser user, String token, String sessionId, String loginIp) {
        SysLoginLog log = new SysLoginLog();
        log.setTenantId(user.getTenantId());
        log.setUserId(user.getId());
        log.setLoginName(user.getLoginName());
        log.setUserType(user.getUserType());
        log.setLoginTime(LocalDateTime.now());
        log.setLoginIp(loginIp);
        log.setLoginRemarks("成功登录");
        log.setToken(token);
        log.setSessionId(sessionId);
        log.setStatus(1);
        super.save(log);
        return log;
    }
    
    @Transactional(rollbackFor=Exception.class)
    public void addLoginoutLog(Integer loginId, String remarks) {
        if (loginId == null) return;
        SysLoginLog update = new SysLoginLog();
        update.setId(loginId);
        update.setLogoutTime(LocalDateTime.now());
        update.setLogoutRemarks(remarks);
        update.setStatus(2);
        super.updateById(update);
    }
    
    public List<SysLoginLog> selectOnlineLoginLog(String loginName, Integer userType) {
        QueryWrapper<SysLoginLog> query = new QueryWrapper<SysLoginLog>();
        query.eq("login_name", loginName).eq("user_type", userType).eq("status", 1);
        return super.list(query);
    }
    
    public List<SysLoginLog> list(Map<String, String> param) {
        QueryWrapper<SysLoginLog> query = new QueryWrapper<SysLoginLog>();
        query.eq("tenant_id", param.get("tenantId"));
        query.orderByDesc("id");
        
        if (StringUtils.isNotBlank(param.get("loginName"))) {
            query.like("login_name", "%" + param.get("loginName") + "%");
        }
        if (StringUtils.isNotBlank(param.get("startDate"))) {
            query.ge("login_time", DateUtils.parseDate(param.get("startDate")));
        }
        if (StringUtils.isNotBlank(param.get("endDate"))) {
            query.le("login_time", DateUtils.parseDate(param.get("endDate") + " 23:59:59"));
        }
        
        return super.list(query);
    }
}
